<?php
include_once('config/config.php');
if($_POST)
{
    $username = $_POST['username'];
    // 判断接收数据是否为空
    if(empty($username))
    {
        ShowMsg('用户不能为空');
    }

    if(empty($_POST['password']))
    {
        ShowMsg('密码不能为空');
    }

    if(empty($_POST['verify']))
    {
        ShowMsg('验证码不能为空');
    }

    if(strtoupper($_SESSION['verify']) != strtoupper($_POST['verify']))
    {
        ShowMsg('验证码错误，请重新输入');
    }

    /* 
        去数据表是否找到用户 -> 说明这个用户存在 -> 判断数据表存放的密码与用户输入密码是否一致 -> 说明登录成功 -> 存储当前登录用户信息 -> 跳转后台
    */
    $findSql = "SELECT * FROM `stu_admin` WHERE `username` = '$username'";

    $Admin = find($findSql);

    if(!$Admin)
    {
        ShowMsg('用户不存在');
    }

    $password = md5($_POST['password'].$Admin['salt']);

    if($password != $Admin['password'])
    {
        ShowMsg('密码错误，请重新输入');
    }

    // 封装用户信息
    $data = [
        'id' => $Admin['id'],
        'username' => $Admin['username'],
        'avatar' => $Admin['avatar']
    ];
    
    // $code = md5($Admin['id'].$Admin['salt']);

    // json_encode => 转成json的字符
    setcookie('LoginAdmin',json_encode($data));
    
    ShowMsg('登录成功','index.php');
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php') ?>
</head>

<style>
    body{
        background-image: none;
        background-color: skyblue !important;
    }
</style>

<body>
    <!--<![endif]-->

    <div class="navbar">
        <div class="navbar-inner">
            <a class="brand" href="index.php"><span class="second">学生成绩管理系统</span></a>
        </div>
    </div>

    <div class="row-fluid">
        <div class="dialog">
            <div class="block">
                <p class="block-heading">登录</p>
                <div class="block-body">
                    <form method="post">
                        <label>用户名</label>
                        <input type="text" class="span12" name="username" placeholder="请输入用户名">
                        <label>密码</label>
                        <input type="password" class="span12" name="password" placeholder="请输入密码">

                        <!-- 验证码 -->
                        <label>验证码</label>
                        <div class="code_box">
                            <input type="text" name="verify" placeholder="请输入验证码">
                            <img src="config/imgcode.php" alt="" onclick="this.src = 'config/imgcode.php'">
                        </div>


                        <!-- 提交按钮 -->
                        <button class="btn btn-primary pull-right">登录</button>
                        <div class="clearfix"></div>
                    </form>
                </div>
            </div>
        </div>
    </div>

</body>

</html>

<?php include_once('common/script.php') ?>